package com.service.impl;

import com.controller.vo.Node;
import com.controller.vo.State;
import com.mapper.MenuMapper;
import com.mapper.PermissionMapper;
import com.pojo.Menu;
import com.service.PermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@Service("permissionService")
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private MenuMapper menuMapper;
    @Override
    public Map<Menu, List<Menu>> searchNav(String roleId) {
        Map<Menu,List<Menu>> map = new TreeMap<>();
        List<Integer> menuIds=permissionMapper.searchByRole(roleId);
        for (Integer mid01:menuIds){
            Menu menu01=menuMapper.getMenu(mid01);
            if(menu01.getMenuParent().equals("0")){
                List<Menu> list =new ArrayList<Menu>();
                map.put(menu01,list);
                for (Integer mid02:menuIds){
                    Menu menu02 = menuMapper.getMenu(mid02);
                    if(menu02.getMenuParent().equals(menu01.getMenuNum())){
                        list.add(menu02);
                    }
                }

            }
        }
        return map;
    }


    @Transactional(readOnly =true)
    public List<Node> search4Tree(String rid) {
        List<Node> list =new ArrayList<>();
        List<Integer> meunId=permissionMapper.searchByRole(rid);


        List<Menu> menus=menuMapper.searchLevel01();


        for (Menu m01:menus) {
            Node node01=new Node();
            node01.setId(m01.getMenuId());
            node01.setText(m01.getMenuName());
            State state = new State();
            node01.setState(state);
            if(meunId.contains((m01.getMenuId()))){
                state.setChecked(true);
            }
            node01.setState(state);
            for (Menu m02:m01.getChildren()) {
                Node node02=new Node();
                node02.setId(m02.getMenuId());
                node02.setText(m02.getMenuName());
                State state2=new State();
                if(meunId.contains(m02.getMenuId())){
                    state2.setChecked(true);
                }
                node02.setState(state2);
                node02.setNodes(null);

                node01.getNodes().add(node02);

            }
            list.add(node01);
        }
        return list;
    }

    @Override
    public void gran4Role(String rid, String[] mids) {
       permissionMapper.delPermission(rid);
        for (String mid:  mids) {
            permissionMapper.addPermission(rid,mid);
        }
    }
}

